﻿using B.S.GridManage.Api.Read.Application.Command.PhisicalGrid;
using B.S.GridManage.Api.Read.Dtos;
using B.S.GridManage.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.XSSF.UserModel;


namespace B.S.GridManage.Api.Read.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        private readonly IMediator mediator;

        public UploadController(IMediator mediator)
        {
            this.mediator = mediator;
        }

        /// <summary>
        /// 导入物理网格接口
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task< ApiResult<int>> ImportGrid(IFormFile file) {

            List<Dtos.CopyPhysicalGridDto> dtos = new List<Dtos.CopyPhysicalGridDto>();//定义一个列表,用来装载Excel中扫描的数据

            using (var ms= new MemoryStream())//实例化内存流
            {
                file.CopyTo(ms);//把文件写入到内存中
                ms.Position = 0;//我也不知道
                //把文件流放到excel
                XSSFWorkbook wb = new XSSFWorkbook(ms);//用npoi加载流
                var sheet = wb.GetSheet("物理网格");//取sheet
                var rownum = sheet.LastRowNum;//最后一行的行号   17 
                for (int i = 1; i < rownum; i++) {//循环每一条,第一行列名
                    CopyPhysicalGridDto dto = new CopyPhysicalGridDto();//实例化要复制的物理网格dto
                    dto.GridCode = sheet.GetRow(i).GetCell(1).ToString(); //给dto里的每一个属性复制
                    dto.AreaId = Convert.ToInt64( sheet.GetRow(i).GetCell(3).ToString());
                    dto.GridName = sheet.GetRow(i).GetCell(2).ToString();
                    dtos.Add(dto);
                }
            }

            CopyPhsicalGridCommand command = new CopyPhsicalGridCommand();
            command.dtos = dtos;   
            return await mediator.Send(command);
        }
    }
}
